package com.xywh.wanandroid.compose_ui.system

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Divider
import androidx.compose.material3.FabPosition
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SecondaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.xywh.composeLibrary.ext.ListFloatingActionButton
import com.xywh.composeLibrary.view.XxTopAppBarCenter
import com.xywh.wanandroid.compose_ui.main.ArticleItem
import com.xywh.wanandroid.data.model.bean.ArticleItem
import com.xywh.wanandroid.data.model.bean.KnowledgeTreeItem
import com.xywh.wanandroid.viewmodel.KnowledgeComposeViewModel

@Composable
fun KnowledgeScreen(
    knowledgeComposeViewModel: KnowledgeComposeViewModel = hiltViewModel(),
    title: String,
    itemData: KnowledgeTreeItem,
    updateMainScreenCollectListData: () -> Unit,
    navigateUp: () -> Unit,
    navigateWebView: (String, String) -> Unit
) {
    val listState = rememberLazyListState()


    XxTopAppBarCenter(
        title = title,
        navigationIconOnClick = { navigateUp.invoke() },
        content = { innerPadding ->
            if (itemData.children.isNotEmpty()) {

                val knowledgeArticles =
                    knowledgeComposeViewModel.knowledgeArticles.value?.collectAsLazyPagingItems()

                if (knowledgeComposeViewModel.cid == 0) {
                    knowledgeComposeViewModel.cid = itemData.children[0].id
                    knowledgeComposeViewModel.getKnowledgeArticles()
                }

                KnowledgeContent(
                    itemData,
                    listState,
                    innerPadding,
                    knowledgeArticles,
                    favoriteOnClick = { id, collect ->
                        if (collect) {
                            knowledgeComposeViewModel.cancelCollectArticle(
                                id,
                                updateMainScreenCollectListData
                            )
                        } else {
                            knowledgeComposeViewModel.addCollectArticle(
                                id,
                                updateMainScreenCollectListData
                            )
                        }
                    },
                    navigateWebView = navigateWebView
                ) {
                    knowledgeComposeViewModel.cid = it
                    knowledgeComposeViewModel.getKnowledgeArticles()
                }
            }


        },
        floatingActionButtonPosition = FabPosition.End,
        floatingActionButton = {
            ListFloatingActionButton(rememberCoroutineScope(), listState)
        })
}


@Composable
@OptIn(ExperimentalMaterialApi::class)
fun KnowledgeContent(
    knowledgeTreeItem: KnowledgeTreeItem,
    listState: LazyListState,
    innerPadding: PaddingValues,
    knowledgeArticles: LazyPagingItems<ArticleItem>?,
    navigateWebView: (String, String) -> Unit,
    favoriteOnClick: (Int, Boolean) -> Unit,
    tabOnclick: (Int) -> Unit
) {


    val refresh by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullRefreshState(refresh, {
        knowledgeArticles?.refresh()
    })
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {

        Column(Modifier.fillMaxSize()) {
            var state by rememberSaveable { mutableStateOf(0) }

            val knowledgeTreeTab = arrayListOf<String>()
            knowledgeTreeItem.children.forEach {
                knowledgeTreeTab.add(it.name)
            }

            if (knowledgeTreeTab.size > 0) {
                SecondaryScrollableTabRow(
                    modifier = Modifier
                        .padding(top = innerPadding.calculateTopPadding())
                        .fillMaxWidth(),
                    selectedTabIndex = state,
                    containerColor = MaterialTheme.colorScheme.primary,
                    contentColor = Color.White,
                    edgePadding = 0.dp,
                    divider = { HorizontalDivider(color = Color.Transparent) },
                    indicator = { tabPositions ->
                        TabRowDefaults.SecondaryIndicator(
                            Modifier.tabIndicatorOffset(tabPositions[state]),
                            color = Color.White
                        )
                    }
                ) {
                    knowledgeTreeTab.forEachIndexed { index, projectTreeItem ->
                        Tab(
                            selected = state == index,
                            onClick = {
                                state = index
                                tabOnclick.invoke(knowledgeTreeItem.children[index].id)
                            },
                            text = {

                                val fontWeight = if (state == index) {
                                    FontWeight.Bold
                                } else {
                                    FontWeight.Normal
                                }
                                Text(projectTreeItem, fontWeight = fontWeight)

                            }
                        )
                    }
                }
            }

            LazyColumn(
                state = listState,
                // consume insets as scaffold doesn't do it by default
                modifier = Modifier
                    .consumeWindowInsets(innerPadding),
//            contentPadding = innerPadding,
            ) {

                knowledgeArticles?.let {
                    items(
                        count = knowledgeArticles.itemCount,
                        key = { index ->
                            val knowledgeArticle = knowledgeArticles[index]
                            "${knowledgeArticle?.id ?: ""}${index}"
                        }) {
                        val itemData = knowledgeArticles[it] ?: return@items
                        ArticleItem(
                            itemData,
                            false,
                            favoriteOnClick = favoriteOnClick
                        ) { title, link ->
                            navigateWebView.invoke(title, link)
                        }

                    }
                }

            }
        }
        PullRefreshIndicator(
            refresh,
            pullRefreshState,
            Modifier.align(Alignment.TopCenter),
            scale = true
        )
    }
}

@Composable
fun KnowledgeTreeItem(
    itemArticle: KnowledgeTreeItem,
    itemOnClick: (title: String, link: Int) -> Unit,
) {
    ListItem(
        modifier = Modifier
            .clickable {
                itemOnClick.invoke(itemArticle.name, itemArticle.id)
            },
        headlineContent = {
            var desc = ""
            itemArticle.children.forEach {
                desc += it.name + "  "
            }
            Text(
                desc,
                fontSize = 12.sp,
                color = Color.Gray,
                modifier = Modifier
                    .padding(top = 5.dp)
                    .fillMaxWidth(),
                maxLines = 1, overflow = TextOverflow.Ellipsis
            )
        },
        overlineContent = {
            Text(
                itemArticle.name,
                fontSize = 14.sp,
                color = Color.Black,
                modifier = Modifier
                    .fillMaxWidth(),
                maxLines = 1, overflow = TextOverflow.Ellipsis
            )
        },
//        supportingContent = {
//            Column(Modifier.fillMaxWidth()) {
//
//            }
//        },
//        leadingContent = {
//
//        },
        trailingContent = {

            Icon(
                Icons.AutoMirrored.Filled.KeyboardArrowRight,
                contentDescription = "Localized description",
                tint = Color.Gray
            )

        }
    )
    Divider()
}
